import { Image, Button, Toast } from 'antd-mobile'
import { getQrcode, updateQrcode } from '@api'
import { useEffect, useState } from 'react'
import { uploadFileToOSS } from '@utils/upload'
import './index.scss'

function App() {
    const [image, setImage] = useState('')

    useEffect(() => {
        getData()
    }, [])

    const getData = () => {
        getQrcode().then(({ success, data }) => {
            if (success && data) {
                setImage(data)
            }
        })
    }

    const handleFileChange = async (e) => {
        const files = Array.from(e.target.files);
        // 限制只能上传一个文件
        if (files.length > 1) {
            Toast.show('只能上传一个文件！');
            return;
        }
        console.log(files)
        Toast.show({
            content: '正在上传~',
            icon: 'loading',
            duration: 0,
            maskClickable: false
        })
        const { res } = await uploadFileToOSS({ file: files[0] })
        try {
            console.log(res.requestUrls[0].split('?')[0])
            Toast.clear()
            updateQrcode({ url: res.requestUrls[0].split('?')[0] }).then(({ success, info }) => {
                Toast.show(info)
                if (success) {
                    getData()
                }
            })
        } catch (error) {
            Toast.clear()
            throw new Error(error)
        }
    };
    return (
        <div className='Photo'>
            <Image src={image}></Image>
            <input
                type="file"
                accept="*/*"  // 允许所有文件类型
                multiple
                style={{ display: 'none' }}
                onChange={handleFileChange}
                id="file-upload-input"
            />
            <div className='Phone_btn'>
                <Button color="primary" onClick={() => document.getElementById('file-upload-input').click()}>
                    编辑或修改二维码图片
                </Button>
            </div>
        </div>
    )
}

export default App
